package com.gzt.bookcatalog.mapper;

import com.gzt.bookcatalog.dto.BookRequestDTO;
import com.gzt.bookcatalog.dto.BookResponseDTO;
import com.gzt.bookcatalog.model.Book;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.stream.Collectors;

@Mapper(componentModel = "spring")
public interface BookMapper {
    BookMapper INSTANCE = Mappers.getMapper(BookMapper.class);

    BookResponseDTO toDto(Book book);

    void updateBookFromDto(BookRequestDTO bookRequestDTO, @MappingTarget Book existingBook);

    default Page<BookResponseDTO> toPageDtoList(Page<Book> books) {
        // 获取分页信息
        Pageable pageable = books.getPageable();
        // 将 Book 列表转换为 BookResponseDTO 列表
        List<BookResponseDTO> dtoList = books.getContent().stream()
                .map(this::toDto)
                .collect(Collectors.toList());
        // 创建新的 Page 对象
        return new PageImpl<>(dtoList, pageable, books.getTotalElements());
    }


}